const config=require('../config/config');
const router = require('koa-router')();
const events=require('events');
const crypto=require('crypto');
const {User}=require('../modles/index');
const isLoggedout=require('../middlewares/isLoggedout');

router.get('/',isLoggedout(), async (ctx, next) => {
    await ctx.render('reg', {
        title: [ctx.locals.name, 'Reg'].join('-'),
        loginUser: ctx.session.loginUser,
        success: ctx.flash.success,
        error: ctx.flash.error
    });
});

router.post('/',isLoggedout(),async (ctx,next)=>{
    let {username,password,repeat}=ctx.request.body,ee=new events();
    ee.on('fail',msg=>{
        ctx.flash={error:msg};
        ctx.redirect('back');
    });
    if(!username || !password)return ee.emit('fail','用户名或密码未输入');
    if(password!==repeat)return ee.emit('fail','密码输入不一致');
    let same=await User.findOne({username});
    if(same)return ee.emit('fail','用户名已经注册');
    new User({
        username,
        password:crypto.createHash('md5').update([password,config.secret].join()).digest('hex'),
        regTime:new Date()
    }).save();
    ctx.flash={success:'注册成功，请登录'};
    ctx.redirect('/login');
});

module.exports = router;